package com.iflytek.testtoastwindow;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;

import com.iflytek.testtoastwindow.utils.AppTools;


/**
 * <b>可拖拽的view</b>
 * 
 * @author leisu@iflytek.com
 * @since 2015年11月24日 下午2:11:15
 */
@SuppressLint("ClickableViewAccessibility")
public class DraggableFrameLayout extends AbsoluteLayout {

	public DraggableFrameLayout(Context context) {
		super(context);
	}

	public DraggableFrameLayout(Context context, AttributeSet attrs,
			int defStyleAttr) {
		super(context, attrs, defStyleAttr);
	}

	public DraggableFrameLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	private boolean isDraggable = true;


	public boolean isDraggable() {
		return isDraggable;
	}

	public void setDraggable(boolean isDraggable) {
		this.isDraggable = isDraggable;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) 
	{
		if(isDraggable)
		{
			if(null == v)
			{
				v = getChildAt(0);
				lp = (LayoutParams) v.getLayoutParams();
			}

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				// 手指按下时记录必要数据,纵坐标的值都需要减去状态栏高度
				xInView = event.getX();
				yInView = event.getY() - lp.y;
				xDownInScreen = event.getRawX();
				yDownInScreen = event.getRawY() - getStatusBarHeight();

				xInScreen = event.getRawX();
				yInScreen = event.getRawY() - getStatusBarHeight();
				break;
			case MotionEvent.ACTION_MOVE:
				xInScreen = event.getRawX();
				yInScreen = event.getRawY() - getStatusBarHeight();

				// 手指移动的时候更新小悬浮窗的位置
				updateViewPosition();
				break;
			case MotionEvent.ACTION_UP:
				// 如果手指离开屏幕时，xDownInScreen和xInScreen相等，且yDownInScreen和yInScreen相等，则视为触发了单击事件。
				if (xDownInScreen == xInScreen && yDownInScreen == yInScreen) {
				}
				break;
			default:
				break;
			}
			return true;
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 记录当前手指位置在屏幕上的横坐标值
	 */
	private float xInScreen;

	/**
	 * 记录当前手指位置在屏幕上的纵坐标值
	 */
	private float yInScreen;

	/**
	 * 记录手指按下时在屏幕上的横坐标的值
	 */
	private float xDownInScreen;

	/**
	 * 记录手指按下时在屏幕上的纵坐标的值
	 */
	private float yDownInScreen;

	/**
	 * 记录手指按下时在小悬浮窗的View上的横坐标的值
	 */
	private float xInView;

	/**
	 * 记录手指按下时在小悬浮窗的View上的纵坐标的值
	 */
	private float yInView;
	
	WindowManager mWindowManager;

	private View v;
	LayoutParams lp;
	int i=0;

	private static final float LIMIT_MIN_Y_PERCENT = 0.7f;
	private int minY = -1;
	private int maxY = -1;

	/**
	 * 是否有拖出屏幕限制
	 */
	private boolean isDragScreenLimit = true;

	/**
	 * 设置是否有拖出屏幕限制
	 * @param isDragScreenLimit
	 */
	public void setDragScreenLimit(boolean isDragScreenLimit)
	{
		this.isDragScreenLimit = isDragScreenLimit;
	}

	/**
	 * 更新小悬浮窗在屏幕中的位置。
	 */
	private void updateViewPosition()
	{
		if(minY==-1)
		{
			minY = 0;
		}

		if(maxY==-1)
		{
			maxY = AppTools.getScreenHeight(getContext()) - this.getHeight() - getStatusBarHeight();
		}

		if(null == v)
		{
			v = getChildAt(0);
			lp = (LayoutParams) v.getLayoutParams();
		}

		int x = (int) (xInScreen - xInView);
		int y = (int) (yInScreen - yInView);


		if(y <=0 )
		{
			y = 0;
		}
		else if(y>=maxY)
		{
			y = maxY;
		}
		if(null == mWindowManager)
		{
			mWindowManager = (WindowManager) getContext()
					.getApplicationContext().getSystemService(
							Context.WINDOW_SERVICE);
		}
		WindowManager.LayoutParams wmParams = (WindowManager.LayoutParams) getLayoutParams();
		wmParams.x = x;
		wmParams.y = y;
		mWindowManager.updateViewLayout(this, wmParams);

		currentX = x;
		currentY = y;

		if(y==minY)
		{
			if(!isDragScreenLimit)
			{
				int yy = (int) (yInScreen - yInView);

				int limitMinY = (int) (v.getHeight() * LIMIT_MIN_Y_PERCENT);
				if(Math.abs(yy) > limitMinY)
				{
					yy = yy < 0 ? -limitMinY : limitMinY;
				}

				if(i%2==0)
				{
					lp.y = yy;
					v.setLayoutParams(lp);
				}
				++i;
			}
		}
		else if(y ==maxY)
		{
//			int yy = (int) (yInScreen - yInView);
//			//yy = yy - maxY;
//			if(null == v)
//			{
//				v = getChildAt(0);
//				lp = (LayoutParams) v.getLayoutParams();
//			}
//
//			if(i%2==0)
//			{
//				lp.y = yy;
//				v.setLayoutParams(lp);
//			}
//			++i;
		}
		else
		{
			if(i%2==0 && lp.y!=0)
			{
				lp.y = 0;
				v.setLayoutParams(lp);
			}
			++i;
		}


	}

	private int currentX,currentY;

	@Override
	protected void onDetachedFromWindow()
	{
		super.onDetachedFromWindow();

//		// 保存配置项
//		AppPreferences.instance(getContext()).putInt(
//				AppPreferences.PreferenceKey.PHONE_SHOW_WINDOW_POSITION_X,
//				currentX);
//		AppPreferences.instance(getContext()).putInt(
//				AppPreferences.PreferenceKey.PHONE_SHOW_WINDOW_POSITION_Y,
//				currentY);
	}

	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();


//		currentX= AppPreferences.instance(
//				getContext()).getInt(
//				AppPreferences.PreferenceKey.PHONE_SHOW_WINDOW_POSITION_X, 0); // 读取配置项
//		currentY = AppPreferences.instance(
//				getContext()).getInt(
//				AppPreferences.PreferenceKey.PHONE_SHOW_WINDOW_POSITION_Y, 0); // 读取配置项

		if(null == mWindowManager)
		{
			mWindowManager = (WindowManager) getContext()
					.getApplicationContext().getSystemService(
							Context.WINDOW_SERVICE);
		}

		WindowManager.LayoutParams wmParams = (WindowManager.LayoutParams) getLayoutParams();
		wmParams.x = currentX;
		wmParams.y = currentY;
		mWindowManager.updateViewLayout(this, wmParams);
	}

	/**
	 * 记录系统状态栏的高度
	 */
	private static int statusBarHeight = -1;

	/**
	 * 用于获取状态栏的高度。
	 * 
	 * @return 返回状态栏高度的像素值。
	 */
	private int getStatusBarHeight() 
	{
		if(statusBarHeight==-1)
		{
			statusBarHeight = AppTools.getStatusBarHeight(getContext());
		}
		return statusBarHeight;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if(null != onKeyEventListener)
		{
			switch (event.getAction()) {
				case KeyEvent.ACTION_DOWN:
					onKeyEventListener.onKeyDown(event.getKeyCode(), event);
					break;
				case KeyEvent.ACTION_UP:
					onKeyEventListener.onKeyUp(event.getKeyCode(), event);
					break;
				default:
					break;
			}
		}
		return super.dispatchKeyEvent(event);
	}


	public void setOnKeyEventListener(OnKeyEventListener onKeyEventListener) {
		this.onKeyEventListener = onKeyEventListener;
	}

	private OnKeyEventListener onKeyEventListener;

	public interface OnKeyEventListener
	{
		boolean onKeyDown(int keyCode, KeyEvent event);

		boolean onKeyUp(int keyCode, KeyEvent event);
	}
}
